﻿#region

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;

#endregion

namespace Jiubang.Wap.HttpModules {
    ///<summary>
    ///</summary>
    public sealed class WapedModule : IHttpModule {
        /// <summary>
        /// 预留多个waped的情况
        /// </summary>
        private static readonly Dictionary<int, List<string>> exceptions = new Dictionary<int, List<string>>(1);
        private static readonly Dictionary<int, string> wapedRedirects = new Dictionary<int, string>(1);
        private static readonly string appDomainappVirtualPath;

        static WapedModule() {
            appDomainappVirtualPath = ConfigurationManager.AppSettings["Host"];
            if (string.IsNullOrEmpty(appDomainappVirtualPath))
                appDomainappVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
            if (appDomainappVirtualPath.EndsWith("/")) appDomainappVirtualPath.Remove(appDomainappVirtualPath.Length - 1, 1);
            exceptions[9] = GetFilterPages(9);
            wapedRedirects[9] = ConfigurationManager.AppSettings["IphoneFilterLinks"];
        }

        #region IHttpModule Members

        ///<summary>
        ///</summary>
        ///<param name = "context"></param>
        public void Init(HttpApplication context) {
            context.BeginRequest += WapedFilter;
        }

        ///<summary>
        ///</summary>
        public void Dispose() {
        }

        #endregion

        private static List<string> GetFilterPages(int waped) {
            var s = ConfigurationManager.AppSettings["Waped" + waped + "HtmlPages"];
            if (string.IsNullOrEmpty(s)) return new List<string>(0);
            var items = s.Split(',');
            var list = new List<string>(items.Length);
            foreach (var item in items) {
                list.Add(item.Trim());
            }
            return list;
        }

        private static void WapedFilter(object sender, EventArgs e) {
            var context = ((HttpApplication)sender).Context;

            int waped;
            int.TryParse(context.Request.QueryString["waped"], out waped);

            if (waped != 9)
                return;

            List<string> list;
            if (!exceptions.TryGetValue(waped, out list))
                return;

            var url = context.Request.Url.AbsoluteUri;
            if (!url.StartsWith("http://")) {
                if (url.StartsWith("/")) url = appDomainappVirtualPath + url;
                else url = appDomainappVirtualPath + "/" + url;
            }

            foreach (var s in list) {
                if (url.IndexOf(s) != -1) 
                    continue;

                string prefix;
                if (!wapedRedirects.TryGetValue(waped, out prefix)) 
                    continue;

                context.Response.Redirect(prefix + HttpUtility.UrlEncode(url));
            }
        }
    }
}